package com.bootdo.common.task;

import com.bootdo.enums.SubscribeStatus;
import com.bootdo.system.dao.BreachRuleStatDao;
import com.bootdo.system.dao.SubscribeRecordDao;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.BreachRuleStatDO;
import com.bootdo.system.domain.SubscribeRecordDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.util.DatePattern;
import com.bootdo.util.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ClearJob implements Job{

    @Autowired
    private SubscribeRecordDao subscribeRecordDao;
    @Autowired
    private BreachRuleStatDao breachRuleStatDao;
    @Autowired
    private UserDao userDao;

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        List<SubscribeRecordDO> list = subscribeRecordDao.list2();
        for (SubscribeRecordDO item : list){
            // 数据设置为爽约
            SubscribeRecordDO recordDO = new SubscribeRecordDO();
            recordDO.setId(item.getId());
            recordDO.setStatus(SubscribeStatus.Four.getSign());
            subscribeRecordDao.update(recordDO);

            // 统计数据判断
            String date = DateUtils.toString(item.getSeeTime(), DatePattern.YMD);
            BreachRuleStatDO breachRuleStatDO = breachRuleStatDao.get(item.getUserId(), date);
            if(breachRuleStatDO == null){
                breachRuleStatDO = new BreachRuleStatDO();
                breachRuleStatDO.setUserId(item.getUserId());
                breachRuleStatDO.setDate(date);
                breachRuleStatDO.setBreakTimes(1);
                breachRuleStatDO.setCancleTimes(0);
                breachRuleStatDao.save(breachRuleStatDO);
            }else{
                breachRuleStatDO.setBreakTimes(breachRuleStatDO.getBreakTimes() + 1);
                breachRuleStatDao.update(breachRuleStatDO);
            }

            // 如果一个月爽约 3 次， 加入黑名单
            if(breachRuleStatDO.getBreakTimes() >= 3){
                UserDO update = new UserDO();
                update.setUserId(item.getUserId());
                update.setBlock(1);
                userDao.update(update);
            }
        }
    }

}